package itbour.onetouchshow.activity.userinfo;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.andview.adapter.BaseRecyclerHolder;
import com.google.gson.Gson;
import com.lsjr.utils.NetUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.utils.permission.Permission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.BaseRefreshAdapter;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.GetPath;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 * <p>
 * 用户意见反馈
 */

public class FeedBackActivity extends MVPBaseActivity<UserinfoContract.View, UserinfoPresenter> implements UserinfoContract.View {


    @BindView(R.id.id_submit)
    TextView idSubmit;
    @BindView(R.id.id_ed_content)
    EditText idEdContent;
    @BindView(R.id.id_ed_device_info)
    EditText idEdDeviceInfo;

    @BindView(R.id.rv_ig)
    RecyclerView rvImage;
    @BindView(R.id.et_phone)
    EditText etPhone;
    FeedBackAdapter feedBackAdapter;
    private List<String> stringList;
    private List<String> upLoadImag = new ArrayList<>();
    private int nowClickImg = -1;

    @Override
    public void loadSucceed(String result) {
        T_.showToastReal("谢谢您的反馈");
        dismissProgressDialog();
        finish();
    }

    @Override
    public void loadFaild(String error) {
        dismissProgressDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_feed_back;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        //初始化recycler 和adapter
        stringList = new ArrayList<>();
        GridLayoutManager layoutManager = new GridLayoutManager(getApplication(), 4);
        stringList.add(R.mipmap.feek_back_add + "");
        feedBackAdapter = new FeedBackAdapter(getApplication(), stringList, R.layout.item_feedback_adapter);
        rvImage.setLayoutManager(layoutManager);
        rvImage.setAdapter(feedBackAdapter);

    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("意见反馈");
        getToolBarView().getLeftimageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeIME(idEdContent.isFocused() ? idEdContent : (idEdDeviceInfo.isFocused() ? idEdDeviceInfo : etPhone), getViewContext());
                onBackPressed();
            }
        });
    }

    @OnClick({R.id.id_ed_content, R.id.id_ed_device_info, R.id.id_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_ed_content:
                break;
            case R.id.id_ed_device_info:
                break;
            case R.id.id_submit:
                if (idEdContent.getText().toString().length() == 0) {
                    T_.showToastReal("请填写你宝贵的建议");
                    return;
                }

                if (!NetUtils.isConnected(UIUtils.getContext())) {
                    T_.showCustomToast("请检查网络");
                    return;
                }

                showProgressDialogWithText("正在提交");
                //自己读取用户手机的信息
                if (stringList.size() > 1) {
                    upLoadAliyun();
                } else {
                    mPresenter.upLoadFeedBack(idEdContent.getText().toString(),
                            idEdDeviceInfo.getText().toString(), "", etPhone.getText().toString());
                }

                break;
        }
    }

    public void upLoadAliyun() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                stringList.remove(0);
                for (int i = 0; i < stringList.size(); i++) {
                    try {
                        String name1 = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + i;
                        AliRequestUtils.getInstance().setName(name1);
                        App.ossClient.putObject(AliRequestUtils.getInstance().putObjectRequest(stringList.get(i)));
                        String pathName = AppConfig.UPLOAD_ALYUN + name1;
                        upLoadImag.add(pathName);
                    } catch (ClientException e) {
                        e.printStackTrace();
                        T_.showToastWhendebug("上传失败");
                        dismissProgressDialog();
                    } catch (ServiceException e) {
                        e.printStackTrace();
                        T_.showToastWhendebug("上传失败");
                        dismissProgressDialog();
                    }
                }

                if (upLoadImag.size() != 0) {
                    String urlListJson = new Gson().toJson(upLoadImag);
                    L_.e(urlListJson);
                    mPresenter.upLoadFeedBack(idEdContent.getText().toString(),
                            idEdDeviceInfo.getText().toString(), urlListJson, etPhone.getText().toString());
                }

            }
        }).start();
    }

    private void closeIME(EditText editText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    private void gotoSelectPhotoType() {
        int chooseMode = PictureMimeType.ofImage();
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(FeedBackActivity.this)
                .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                //.selectionMedia(false)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(AppConst.TOPHOTO);//结果回调onActivityResult code
    }

    public void setNowClickImg(int nowClickImg) {
        this.nowClickImg = nowClickImg;
    }

    /**
     * 从不同的界面返回 执行不同的操作
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (feedBackAdapter == null) {
            return;
        }
        if (data != null) {
            if (requestCode == AppConst.TOPHOTO) {
//                Uri uri = data.getData();
//                final String path = GetPath.getPath(uri, getApplication());


                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                String imageUrl = null;
                for (LocalMedia media : localMedia) {
                    // Log.e("图片-----》", media.getPath());
                    imageUrl = media.getPath();
                }
                Long fileSizes = GetPath.getFileSizes(new File(imageUrl));
                if (fileSizes != null) {
                    if (fileSizes > InchingDataSingleCase.INSTANCE.getAppControl().getImgMaxSize()) {
                        // T_.showCustomToast("图片过大");
                        new OneToucDialog.Builder(this)
                                .content("图片文件过大，建议选择不超过" + (int) (InchingDataSingleCase.INSTANCE.getAppControl().getImgMaxSize() / 1000 / 1000) + "M的图片")
                                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(OneToucDialog dialog, DialogAction which) {
                            }
                        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                                .cancelable(false)
                                .show();

                        return;
                    }
                }
                //L_.e(path);
                if (stringList.contains(imageUrl)) {
                    return;
                }
                stringList.add(imageUrl);
                feedBackAdapter.notifyDataSetChanged(stringList);
            }
        }
    }

    public class FeedBackAdapter extends BaseRefreshAdapter<String> {

        public FeedBackAdapter(Context context, List<String> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder holder, String var2, int position) {
            ImageView ivFeedback = holder.getView(R.id.iv_feedback);
            ViewGroup.LayoutParams layoutParams = ivFeedback.getLayoutParams();
            layoutParams.width = UIUtils.WHD()[0] / 5;
            layoutParams.height = layoutParams.width;
            ivFeedback.setLayoutParams(layoutParams);
            if (position == 0) {
                ivFeedback.setImageResource(Integer.valueOf(var2));
            } else {
                if (var2 != null) {
                    ImageLoader.getInstance().showImage(FeedBackActivity.this, var2, ivFeedback);
                }
            }


            //在这里调相册
            ivFeedback.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //requestPermissions();
                    //去裁界面
                    if (position == 0) {
                        if (stringList.size() <= 5) {
//                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                            startActivityForResult(intent, AppConst.TOPHOTO);

                            requestPermission(new PermissionListener() {
                                @Override
                                public void onGranted() {
                                    gotoSelectPhotoType();
                                }

                                @Override
                                public void onDenied(List<String> list) {
                                }
                            }, Permission.Group.STORAGE);

                        } else {
                            T_.showToastReal("不能再添加了哟");
                        }

                    }
                }
            });
        }

    }
}
